import os
import exifread
import shutil
import time
import json
import urllib.request

def copyfile(src,dst):
    print("copy",src,"to",dst,"...")
    shutil.copyfile(src,dst)
    print("OK")

def check_label(tags,label):
    if label not in tags.keys():
        print("tags[%s] not found" %(label))
        return False
    return True

def get_date(tags):
    label='EXIF DateTimeOriginal'
    if not check_label(tags,label):
        return ""
    value=str(tags[label])
    dt=time.mktime(time.strptime(value,"%Y:%m:%d %H:%M:%S"))
    ret=time.strftime("%Y%m%d", time.localtime(dt))
    return ret

#获取经度或纬度
def getLatOrLng(tags, refKey, tudeKey):
    if refKey not in tags:
        return None
    ref=tags[refKey].printable
    LatOrLng=tags[tudeKey].printable[1:-1].replace(" ","").replace("/",",").split(",")
    LatOrLng=float(LatOrLng[0])+float(LatOrLng[1])/60+float(LatOrLng[2])/float(LatOrLng[3])/3600
    if refKey == 'GPS GPSLatitudeRef' and tags[refKey].printable != "N":
        LatOrLng=LatOrLng*(-1)
    if refKey == 'GPS GPSLongitudeRef' and tags[refKey].printable != "E":
        LatOrLng=LatOrLng*(-1)
    return LatOrLng

#调用百度地图API通过经纬度获取位置
def get_location(lat,lng):
    url = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=wgs84ll&location=%s,%s' %('in3u3EdIaGYw7M6Kxz4g0yb25QhSBXve',str(lat),str(lng))
    req = urllib.request.urlopen(url)
    res = req.read().decode("utf-8") 
    str_value = json.loads(res)
    #print(str)
    ###formatted_address, city
    jsonResult = str_value.get('result')
    #care_key="city"
    ret = jsonResult['addressComponent']['city']
    return ret

def get_city(tags):
    lat = getLatOrLng(tags,'GPS GPSLatitudeRef','GPS GPSLatitude') #纬度
    lng = getLatOrLng(tags,'GPS GPSLongitudeRef','GPS GPSLongitude') #经度
    if not lat or not lng:
        return ""
    return get_location(lat,lng)
    
def get_model(tags):
    label='Image Model'
    if not check_label(tags,label):
        return ""
    value=str(tags[label])
    return value

def merge_name(eles):
    ret=""
    for ele in eles:
        if not ele:
            continue
        ele=ele.replace(' ','_')
        #print(ele)
        if ret:
            ret+="_%s" %(ele)
        else:
            ret="".join(ele)
    return ret

#照相机制造商 'Image Make'
#照相机型号 'Image Model'
#照片尺寸 'EXIF ExifImageWidth' 'EXIF ExifImageLength'
#

#命名格式: <拍摄时间>_<照相机型号>
#年月日_时分秒_
def rename_one_image(src_image,save_path=None):
    tags={}
    with open(src_image,'rb') as f:
        tags=exifread.process_file(f)
    origin_name=os.path.basename(src_image)
    if not tags:
        print("no tags for",src_image)
        if save_path:
            copyfile(src_image,os.path.join(save_path,origin_name))
        return
    
    name_eles=[]
    func_list=[get_date,get_model,get_city]
    for func in func_list:
        name_eles.append(func(tags))
    suffix=os.path.splitext(src_image)[-1]
    merge_n=merge_name(name_eles)
    final_name="%s%s" %(merge_n,suffix)
    
    dst_path=os.path.dirname(src_image)
    src=src_image
    dst=os.path.join(dst_path,final_name)
    copyfile(src,dst)

